package com.songlei.rtcadriondh265demo.utils

import android.util.Log

// 状态管理类（增加有效性标记）
class BandwidthState {
    var lastValidBytesSent: Long = 0L
    var lastValidTimestampUs: Double = 0.0 // 单位：毫秒
    var isInitialized: Boolean = false // 新增初始化标记
}

fun calculateBandwidth(
    state: BandwidthState,
    currentBytesSent: Long,
    currentTimestampUs: Double // 单位：微秒
): Long? {
    if (!state.isInitialized) {
        state.lastValidBytesSent = currentBytesSent
        state.lastValidTimestampUs = currentTimestampUs
        state.isInitialized = true
        Log.d("Bandwidth", "首次初始化: bytes=$currentBytesSent, ts=$currentTimestampUs μs")
        return null
    }

    // 处理计数器重置
    if (currentBytesSent < state.lastValidBytesSent) {
        Log.d("Bandwidth", "计数器重置: current=$currentBytesSent, last=${state.lastValidBytesSent}")
        state.isInitialized = false
        return null
    }

    val deltaBytes = currentBytesSent - state.lastValidBytesSent
    val deltaTimeUs = currentTimestampUs - state.lastValidTimestampUs

    return when {
        deltaTimeUs <= 0 -> {
            null
        }
        deltaTimeUs < 1000 -> {
            null
        }
        deltaBytes <= 0 -> {
            null
        }
        else -> {
            val deltaTimeSec = deltaTimeUs / 1_000_000.0
            val bps = (deltaBytes * 8) / deltaTimeSec
            // 更新状态
            state.lastValidBytesSent = currentBytesSent
            state.lastValidTimestampUs = currentTimestampUs

            bps.toLong()
        }
    }
}